import { defineStore } from 'pinia'
import { LoginAPI } from '@/api/user'
interface LoginData {
    username: string,
    password: string
}
export const useUserStore = defineStore('user', {
    state: () => ({
        token: sessionStorage.getItem('token') || null,
        username: sessionStorage.getItem('username') || '',
        // 菜单
        menu: sessionStorage.getItem('menu')?JSON.parse(sessionStorage.getItem('menu')!):[],
        // 权限
        roles: sessionStorage.getItem('roles')?JSON.parse(sessionStorage.getItem('roles')!):[]
    }),
    actions: {
        // 登录验证并存入用户信息
        async Login(data: LoginData) {
            const { data: { user: { username, roles }, token, menulist } } = await LoginAPI(data)
            this.token = token
            this.username = username
            this.roles = roles
            this.menu = menulist
            sessionStorage.setItem('token', token)
            sessionStorage.setItem('username', username)
            sessionStorage.setItem('roles', JSON.stringify(roles))
            sessionStorage.setItem('menu', JSON.stringify(menulist))
        },
        // 退出登录清楚token
        clearData() {
            this.token = null
            this.username = ''
            this.roles = []
            this.menu = []
            sessionStorage.clear()
        }
    }
})